<template>
  <div>
    <el-form
      :model="form"
      :rules="rules"
      label-width="100px"
      ref="form"
      class="kylin-form"
    >
    <el-form-item :label="$t('system.task_name')" prop="task_name">
      <el-input v-model="form.task_name"></el-input>
    </el-form-item>
      <el-form-item :label="$t('configure.task_object')" prop="target_type">
        <el-select v-model="form.target_type" size="small">
          <el-option
            v-for="item in targets"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        :label="$t('system.batch')"
        prop="batch"
        v-if="form.target_type === 'batch'"
      >
        <virtual-list
          :value="form.batch"
          :multiple="true"
          size="small"
          :obj="true"
          @selectValue="handleBatchSelect"
          :list="batches"
        ></virtual-list>
      </el-form-item>
      <el-form-item
        :label="$t('system.host')"
        prop="host"
        v-if="form.target_type === 'host'"
      >
        <virtual-list
          :value="form.host"
          :multiple="true"
          size="small"
          :obj="true"
          @selectValue="handleHostSelect"
          :list="hosts"
        ></virtual-list>
      </el-form-item>
      <el-form-item :label="$t('repeat')" prop="repeat">
        <el-select 
          v-model="form.repeat" 
          size="small"
          multiple 
          @change="handleRepeatSelectChange">
          <el-option
            v-for="item in repeatTime"
            :key="item.name"
            :value="item.name"
            :label="item.name"
            :disabled="item.disabled">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('time')" prop="time">
        <div
          :style="{ marginBottom: '6px' }"
          v-for="(item, index) in form.time.length"
          :key="index">

          <el-time-picker
            is-range
            v-model="form.time[index].value"
            value-format="HH:mm:ss"
            format="HH:mm:ss"
            :range-separator="$t('to')"
            :start-placeholder="$t('start_time')"
            :end-placeholder="$t('end_time')"
            :placeholder="$t('choose_time_range')">
          </el-time-picker>
          <el-button @click="handleDeleteTime(index)">-</el-button>
        </div>
        <el-button @click="handleAddTime">+</el-button>
      </el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">{{ $t("cancel") }}</el-button>
      <el-button
        class="kylin-button"
        @click="handleConfirm"
        v-loading="loading"
        >{{ $t("confirm") }}</el-button
      >
    </div>
  </div>
</template>

<script>
import virtualList from "@/components/virtualList";
import { createScanSetList, getBatchsList, getHostIpList, getScanSetDetails, updateScanSet } from "@/api/scan";
export default {
  components: {
    virtualList,
  },
  props: {
    edit_id: {
      default: null,
    },
  },
  data() {
    return {
      action: "#",
      loading: false,
      scanStatus: true,
      targets: [
        { id: "batch", name: this.$t("configure.select_batch") },
        { id: "host", name: this.$t("configure.select_host") },
      ],
      repeatTime: [
        { name: this.$t("not_repeat"), value: ""},
        { name: this.$t("Monday"), value: "" },
        { name: this.$t("Tuesday"), value: "" },
        { name: this.$t("Wednesday"), value: "" },
        { name: this.$t("Thursday"), value: "" },
        { name: this.$t("Friday"), value: "" },
        { name: this.$t("Saturday"), value: "" },
        { name: this.$t("Sunday"), value: "" },
      ],
      hosts: [],
      batches: [],
      form: {
        task_name: '',
        target_type: "batch",
        batch: [],
        host: [],
        repeat: [],
        time: [
          {value: ['', ''],}
        ], 
      },
      rules: {
        task_name: [
          {
            required: true, 
            message: this.$t("system.task_name_require")
          }
        ],
        batch: [
          {
            required: true,
            message: this.$t("system.batch_require"),
            trigger: "change",
          },
        ],
        host: [
          {
            required: true,
            message: this.$t("system.host_require"),
            trigger: "change",
          },
        ],
      },
    };
  },
  mounted() {
    getHostIpList({ paged: false, sortBy: "ip", sortOrder: "asc" }).then((res) => {
      let results = res.data.data;
      let hosts = [];
      results.forEach((item) => {
        hosts.push({
          id: item.id,
          name: item.ip,
        });
      });
      this.hosts = hosts;
    });
    getBatchsList({ paged: false }).then((res) => {
      let results = res.data.data;
      let batches = [];
      results.forEach((item) => {
        batches.push({
          id: item.id,
          name: item.name,
        });
      });
      this.batches = batches;
    });
    // 点击编辑按钮，将要编辑的信息展示到页面
    if(this.edit_id) {
      getScanSetDetails(this.edit_id).then(res => {
        if(res.data.code == '0') {
          let data = res.data.data
          this.form.task_name = data.name;
          this.scanStatus = data.scanStatus;
          this.form.repeat = data.scanWeek != null ? data.scanWeek.split(",") : []

          this.form.target_type = data.type <= 2 ? "host" : "batch"
          if(this.form.target_type === 'host') {
            if(data.kylinHostList != null) {
              data.kylinHostList.map(item => {
                this.form.host.push(item.id)
              })
            } else {
              this.form.host = []
            }
          } else {
            if(data.batchesList != null) {
              data.batchesList.map(item => {
                this.form.batch.push(item.id)
              })
            } else {
              this.form.batch = []
            }
          }

          if(data.scanTime != null) {
            let timeArr = data.scanTime.split(",");
            let time = []
            timeArr.map((item, index) => {
              time[index] = {}
              time[index].value = item.split("~")
            })

            this.form.time = time
          } else {
            this.form.time = [{value: ['', '']}]
          }
          
        } else {
          this.$message({
            type: "error",
            message: res.data.message,
          });
        }
      })
    }
  },
  methods: {
    handleDeleteTime(index) {
      this.form.time.splice(index, 1)
    },
    handleAddTime() {
      this.form.time.push({value: ['', '']})
    },
    // 选择到不重复时，其他选项不可选
    handleRepeatSelectChange(value) {
      if(value.indexOf(this.$t("not_repeat")) > -1) {
        this.form['repeat'] = [this.$t("not_repeat")]
        this.repeatTime.filter(item => item.name != this.$t("not_repeat")).map(item => {
          item.disabled = true
        })
      } else {
        this.repeatTime.filter(item => item.name != this.$t("not_repeat")).map(item => {
          item.disabled = false
        })
      }
    },
    handleHostSelect(value) {
      this.form.host = value;
    },
    handleBatchSelect(value) {
      this.form.batch = value;
    },
    handleCancel() {
      this.$refs.form.resetFields();
      this.$emit("click");
    },
    handleConfirm() {
      this.$refs.form.validate((valid) => {
        let ip = [], batch = []; // 存储选择的主机IP和batch的名称
        if (valid) {
          //form中存储的ip和batch是id但是需要传递的参数是ip和name
          this.hosts.map(item => {
            if(this.form.host.indexOf(item.id) > -1) {
              ip.push(item.name)
            }
          })
          this.batches.map(item => {
            if(this.form.batch.indexOf(item.id) > -1) {
              batch.push(item.id)
            }
          })

          // 需要的传递的属性和值与form中不同，所以需要做处理
          let data = {
            scanStatus: true,
            name: this.form.task_name,
            scanWeek: this.form.repeat.join(),
            type: this.form.target_type == 'host' ? 2 : 3,
            scanTime: '',
            hostsIp: ip.join(),
            batchsId: batch.join(),
          }
          
          this.form.time.map(item => {
            if(item.value[0] !== '' && item.value[1] !== '') {
              let start = item.value[0]
              let end = item.value[1]
              data.scanTime += start + "~" + end + ","
            }
          })
          data.scanTime = data.scanTime.substr(0,data.scanTime.length-1);

          // 判断是更新信息还是新建信息
          if(this.edit_id) {
            data.id = this.edit_id
            updateScanSet(data).then(res => {
              if (res.data.code == "0") {
                  this.$message({
                    type: "success",
                    message: res.data.message,
                  });
                  this.$emit("click", "success");
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message,
                });
              }
            })
          } else {
            createScanSetList(data).then(res => {
              if (res.data.code == "0") {
                  this.$message({
                    type: "success",
                    message: res.data.message,
                  });
                  this.$emit("click", "success");
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message,
                });
              }
            })
          }
        }
      });
    },
  },
  watch: {
    "form.target_type": function () {
      this.$refs.form.clearValidate();
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.size {
  width: 100%;
}
.kylin-form {
  max-height: 400px;
  overflow: auto;
}
</style>